import classNames from 'classnames';
import React from 'react';
import dragOperationSlice from '../redux/toolKitSlice/dragOperation';
import { getEventClientOffset } from '../utils/OffsetUtils';
type ParentName = 'left' | 'right';

interface CardProps {
  id: number;
  text: string;
  index: number;
  store: any;
  parentName: ParentName;
  overIndex?: number;
  onAddCard: (
    inserItem: { id: number; text: string },
    hoverIndex: number,
    targetParentName: ParentName,
  ) => void;
  onMoveCard: (ragIndex: number, hoverIndex: number) => void;
}

function Card(props: CardProps) {
  const {
    id,
    index,
    text,
    store,
    onMoveCard,
    parentName,
    onAddCard,
    overIndex,
  } = props;
  const handleDragStart: React.DragEventHandler<HTMLElement> = (e) => {
    const dragStartDom = e.currentTarget; //事件绑定对象
    const dragId = dragStartDom.id;
    const dragIndex = dragStartDom.dataset.index;
    const dragSouce = { id, text };
    console.log('--handleDragStart--dragId--dragIndex--:', dragId, dragIndex);
    store.dispatch(
      dragOperationSlice.actions.beginDrag({
        dragParentName: parentName,
        dragId,
        dragIndex: Number(dragIndex),
        dragSouce,
      }),
    );

    // setTimeout(() => {
    //   store.dispatch(dragOperationSlice.actions.publishDragSource({}));// opactity === isDragging ? 0 : 1, isDragging立马true导致 drag时浏览器自导的预览dom opacity === 0
    // });
  };

  // const handleDragEnter: React.DragEventHandler<HTMLElement> = (e) => {
  //   console.log('--li--handleDragEnter--');
  //   e.stopPropagation(); //阻止冒泡到ul
  // }

  const handleDragOver: React.DragEventHandler<HTMLElement> = (e) => {
    const operationStore = store.getState().dragOperationStore;
    const { dragId, dragIndex } = operationStore;

    const dragHoverDom = e.currentTarget; //事件绑定对象
    const hoverId = dragHoverDom.id;
    const hoverIndex = Number(dragHoverDom.dataset.index!);

    console.log(
      '--handleDragOver--dragId--dragIndex--hoverId--hoverIndex--:',
      dragId,
      dragIndex,
      hoverId,
      hoverIndex,
    );
    if (dragId === undefined || dragIndex === undefined) {
      //穿梭拖动时--ul--enter--store.dispatch(dragOperationSlice.actions.endDrag({}))--导致dragId/dragIndex === undefined
      e.preventDefault(); //drop执行的条件是 必须先 handleDragOver且在handleDragOver 中  e.preventDefault();
      return;
    }
    if (dragId === hoverId || dragIndex === hoverIndex) {
      // if (e.dataTransfer) {
      //   e.dataTransfer.dropEffect = 'none';  //有回弹效果
      // }
      return;
    }

    const hoverBoundingRect = dragHoverDom.getBoundingClientRect();
    const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2; //高度/2
    const clientOffset = getEventClientOffset(e);
    const hoverDiffy = clientOffset.y - hoverBoundingRect.top;
    // Dragging down
    if (dragIndex < hoverIndex && hoverDiffy < hoverMiddleY) {
      // if (e.dataTransfer) {
      //   e.dataTransfer.dropEffect = 'none';  //有回弹效果
      // }
      return;
    }
    // Dragging upwards
    if (dragIndex > hoverIndex && hoverDiffy > hoverMiddleY) {
      if (e.dataTransfer) {
        e.dataTransfer.dropEffect = 'none'; //有回弹效果
      }
      return;
    }
    // if (e.dataTransfer) {
    //   e.dataTransfer.dropEffect = 'move'
    // }
    e.preventDefault();
    store.dispatch(
      dragOperationSlice.actions.over({
        dropId: hoverId,
        dropIndex: hoverIndex,
        dropParentName: parentName,
        dropEventClientOffset: clientOffset,
      }),
    );
  };

  //鼠标松开的时候才会执行啊
  const handleDrop: React.DragEventHandler<HTMLElement> = (e) => {
    // e.preventDefault();
    const operationStore = store.getState().dragOperationStore;
    const {
      dragParentName,
      dragSouce,
      dragIndex,
      dropIndex: storeHoverIndex,
    } = operationStore;
    if (dragIndex !== storeHoverIndex) {
      const dropDom = e.currentTarget;
      const dropId = dropDom.id;
      const dropIndex = Number(dropDom.dataset.index!);
      if (dragIndex !== dropIndex) {
        if (dragParentName !== parentName) {
          //不能放到handleDragEnd中执行，因为dragStart和dragEnd永远是一个dom,他们的parentName永远相等
          onAddCard(dragSouce, dropIndex, parentName);
        } else {
          onMoveCard(dragIndex, dropIndex);
        }
        console.log('--handleDrop--dropId--dropIndex--:', dropId, dropIndex);
        const clientOffset = getEventClientOffset(e);
        store.dispatch(
          dragOperationSlice.actions.drop({
            dropId,
            dropIndex,
            dropParentName: parentName,
            dropEventClientOffset: clientOffset,
          }),
        );
        setTimeout(() => {
          store.dispatch(dragOperationSlice.actions.endDrag({}));
        }, 50);
      }
    }
  };

  // 左右穿梭时，当前Card已经被删除， handleDragEnd不会执行
  const handleDragEnd: React.DragEventHandler<HTMLElement> = (e) => {
    console.log('--handleDragEnd--');
    store.dispatch(dragOperationSlice.actions.endDrag({}));
  };

  return (
    <li
      className={classNames('sort-card', { active: overIndex === index })}
      id={id.toString()}
      data-index={index.toString()}
      draggable
      onDragStart={handleDragStart}
      // onDragEnter={handleDragEnter}
      onDragOver={handleDragOver}
      onDrop={handleDrop}
      onDragEnd={handleDragEnd}
    >
      {text}-{overIndex}
    </li>
  );
}

export default Card;
